package apps.sim.http;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import apps.sim.Index;
import apps.sim.core.Trapper;

import com.sun.net.httpserver.HttpExchange;

public class HttpOperationHandler extends HttpBaseHandler {

	public void execute(HttpExchange exchange) throws Exception {
		final Map<String, String> params = extractParams(exchange.getRequestURI());
		if (params.size() == 0) {
			final InputStream resourceAsStream = Index.class.getResourceAsStream("http/page/index.html");
			successResponse(exchange, resourceAsStream);
		} else if (params.size() == 1 && params.containsKey("sessionid")) {
			final InputStream resourceAsStream = Index.class.getResourceAsStream("http/page/index.html");
			successResponse(exchange, resourceAsStream);
		} else {
			handleAjaxRequests(exchange, params);
		}

	}

	private void handleAjaxRequests(HttpExchange exchange, final Map<String, String> params) throws Exception {
		if (params.get("enable") != null && "true".equals(params.get("enable"))) {
			enable(params.get("url"), params.get("class"));
		}
		if (params.get("disable") != null && "true".equals(params.get("disable"))) {
			disable(params.get("url"), params.get("class"));
		}
		successResponse(exchange, new ByteArrayInputStream((params.get("rowid") + "_ROW_NUM_done").getBytes()));
	}

	private void disable(String url, String clazz) throws Exception {
		Trapper.removeContext(url, clazz);
	}

	private void enable(String url, String clazz) throws Exception {
		validate(url);
		Trapper.startAndAddContext(url, clazz);
	}

	private void validate(String uri) throws MalformedURLException {
		final URL url = new URL(uri);
		if (!(url.getProtocol().equalsIgnoreCase("http"))) {
			throw new MalformedURLException("Only http simulation is supported.");
		}
		if (!(url.getHost().equalsIgnoreCase("localhost") || !url.getHost().equalsIgnoreCase("127.0.0.1"))) {
			throw new MalformedURLException("Only localhost/127.0.0.1 is supported.");
		}
		if (url.getPort() < 21000 || url.getPort() > 22000) {
			throw new MalformedURLException("Please kepp port range between 21000-22000");
		}
	}
}
